package cn.wolfcode.luowowo.controller;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("users")
public class UserController {

    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.sign}")
    private String smsSign;
    @Value("${sms.appkey}")
    private String smsAppkey;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserInfoRedisService redisService;

    @GetMapping("/get")
    public Object get(String id){
        return userInfoService.get(id);
    }

    @GetMapping("/checkPhone")
    public Object checkPhone(String phone){
        boolean ret = userInfoService.checkPhone(phone);
        return !ret;
    }

    @GetMapping("/sendVerifyCode")
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone,smsUrl,smsSign,smsAppkey);
        return JsonResult.success();
    }

    @RequireLogin  //访问需要登录
    @GetMapping("/getCurrentUser")
    public Object getCurrentUser(HttpServletRequest request){
        //获取请求头里面的token
        String token = request.getHeader("token");

        //通过token判断是否已经登录
        UserInfo userInfo = redisService.getUserByToken(token);

        return JsonResult.success(userInfo);
    }


    @PostMapping("/regist")
    public Object regist(String phone,String nickname,String password,String rpassword,String verifyCode){
        /*//添加业务逻辑
        try {
            userInfoService.regist(phone,nickname,password,rpassword,verifyCode);
            return JsonResult.success();
        } catch (LogicException ex) {
            ex.printStackTrace();
            return new JsonResult(JsonResult.CODE_ERROR_PARAM,ex.getMessage(),null);
        }  catch (Exception ex) {
            ex.printStackTrace();
            return new JsonResult(JsonResult.CODE_ERROR_PARAM,"系统异常,请联系管理员",null);
        }*/
        userInfoService.regist(phone,nickname,password,rpassword,verifyCode);
        return JsonResult.success();

    }
    @PostMapping("/login")
    public Object login(String username,String password){
        UserInfo userInfo = userInfoService.login(username,password);
        //将用户缓存到redis中
        String token = redisService.setToken(userInfo);

        //返回两个数据token,user
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",userInfo);
        return JsonResult.success(map);
    }
}
